package edu.biwu.response;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.*;

/**
 * HttpServletResponse中的方法
 *  getOutputStream():获取一个字节输出流
 * ServletContext中的方法
 *   getMimeType(String fileName):根据指定的名称返回对应的MIME类型
 */
@WebServlet("/resp/demo05")
public class ResponseDemo05 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取字节输出流，并且包转成缓冲流
        ServletOutputStream os = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(os);

        //2.设置响应内容的mime类型
        ServletContext servletContext = getServletContext();
        String mimeType = servletContext.getMimeType("1.jpg");

        //3.告知浏览器响应内容的mime类型
        response.setContentType(mimeType);

        //4.通过字节输出流将内容写给浏览器
        InputStream is = getServletContext().getResourceAsStream("/1.jpg");
        BufferedInputStream bis = new BufferedInputStream(is);

        int b;
        while ((b = bis.read()) != -1) {
            bos.write(b);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
